import { NextRequest, NextResponse } from "next/server"; import { getServerSession } from "next-auth"; import { authOptions } from "@/lib/auth"; import { prisma } from "@/lib/prisma"; // GET /api/appointments/[id] export async function GET( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const { id } = await params; const session = await getServerSession(authOptions); if (!session?.user?.email) { return NextResponse.json({ error: "No autorizado" }, { status: 401 }); } const user = await prisma.user.findUnique({ where: { email: session.user.email }, }); if (!user) { return NextResponse.json({ error: "Usuario no encontrado" }, { status: 404 }); } const appointment = await prisma.appointment.findUnique({ where: { id }, include: { paciente: { select: { id: true, name: true, lastname: true, email: true, profileImage: true, phone: true, }, }, medico: { select: { id: true, name: true, lastname: true, email: true, profileImage: true, }, }, }, }); if (!appointment) { return NextResponse.json({ error: "Cita no encontrada" }, { status: 404 }); } // Validar acceso const canAccess = appointment.pacienteId === user.id || appointment.medicoId === user.id || user.role === "ADMIN"; if (!canAccess) { return NextResponse.json({ error: "No autorizado" }, { status: 403 }); } return NextResponse.json(appointment); } catch (error) { console.error("Error al obtener cita:", error); return NextResponse.json({ error: "Error al obtener cita" }, { status: 500 }); } } // PATCH /api/appointments/[id] - Cancelar cita (paciente) export async function PATCH( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const { id } = await params; const session = await getServerSession(authOptions); if (!session?.user?.email) { return NextResponse.json({ error: "No autorizado" }, { status: 401 }); } const user = await prisma.user.findUnique({ where: { email: session.user.email }, }); if (!user) { return NextResponse.json({ error: "Usuario no encontrado" }, { status: 404 }); } const appointment = await prisma.appointment.findUnique({ where: { id }, }); if (!appointment) { return NextResponse.json({ error: "Cita no encontrada" }, { status: 404 }); } // Solo el paciente puede cancelar if (appointment.pacienteId !== user.id) { return NextResponse.json({ error: "No autorizado" }, { status: 403 }); } const updated = await prisma.appointment.update({ where: { id }, data: { estado: "CANCELADA" }, include: { paciente: { select: { id: true, name: true, lastname: true, email: true, profileImage: true, }, }, medico: { select: { id: true, name: true, lastname: true, email: true, profileImage: true, }, }, }, }); return NextResponse.json(updated); } catch (error) { console.error("Error al cancelar cita:", error); return NextResponse.json({ error: "Error al cancelar cita" }, { status: 500 }); } }